$(document).ready(function () {
    $("#addOrgForm,#updateOrgForm").bootstrapValidator({
        message: 'This value is not valid',
        excluded: [':disabled', ':hidden'], //[':disabled', ':hidden', ':not(:visible)'] //设置隐藏组件可验证
        feedbackIcons: {
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            id: {
                trigger: "change", //针对赋值的文本框执行change事件
                validators: {
                    notEmpty: {
                        message: '父级ID不能为空'
                    }
                }
            },
            orgName: {
                trigger: "change", //针对赋值的文本框执行change事件
                validators: {
                    notEmpty: {
                        message: '请输入组织机构名称'
                    },
                    regexp: {
                        regexp: /^[\u4e00-\u9fa5]+$/,
                        message: '请输入汉字'
                    }
                }
            },
            remark: {
                trigger: "change", //针对赋值的文本框执行change事件
                validators: {
                    regexp: {
                        regexp: /^.{0,50}$/,
                        message: '备注最多可输入50个字符'
                    }
                }
            }
        }
    });

})

/*新增角色及权限时加载权限树结构*/
var setting = {
    view: {
        dblClickExpand: false,
        selectedMulti: false // 禁止多点同时选中的功能
    },
    check: {
        enable: false
    },
    data: {
        key: {
            checked: "checked",
            children: "children",
            name: "orgName",
            title: "",
            url: ""
        },
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "parentId",
            rootPId: ""
        }
    },
    async: {
        enable: true,
        url: "../organ/query",
        dataFilter: filter
    },
    callback: {
        onCheck: onCheck,
        onClick: onClick,
        onAsyncSuccess: onAsyncSuccess,
        onRightClick: OnRightClick
    }
};

function filter(treeId, parentNode, childNodes) {
    if (!childNodes) return null;
    for (var i = 0, l = childNodes.length; i < l; i++) {
        childNodes[i].orgName = childNodes[i].orgName.replace(/\.n/g, '.');
    }
    return childNodes;
}

var zTree, rMenu;
$(document).ready(function () {
    $.fn.zTree.init($("#treeDemo"), setting);
    zTree = $.fn.zTree.getZTreeObj("treeDemo");
    rMenu = $("#rMenu");
    var node = zTree.getNodeByParam("id", 1);
    zTree.selectNode(node);
    zTree.expandNode(node, true, false, false);
    var btnElement = '.orgTitle .dis';
    btnJurisdiction(btnElement);//查询当前用户的按钮权限
});

/*树结构权限复选框点击事件，获取节点id*/
function onCheck(e, treeId, treeNode) {
    var treeObj = $.fn.zTree.getZTreeObj("treeDemo"),
        nodes = treeObj.getCheckedNodes(true),
        v = "";
    for(var i=0;i<nodes.length;i++){
        v+=nodes[i].id+",";  //获取选中节点的值
    }
    return v;
}

function onClick(event, treeId, treeNode, clickFlag) {
    $("#chkVal").val(treeNode.id); //用于判断节点是否被点击
    /*定义一个全局变量存储被点击节点的数据*/
    clickData = treeNode;
    var val = $("#chkType").val(); //用于判断是执行哪种操作
    if (val == "") {
        layer.msg("请选择对此节点执行何种操作");
    }
    if (val == 1) { //新增弹出框
        $("#updateOrgBox").css("display", "none");
        $("#addOrgBox").css("display", "block");
        $("#addOrgForm input[name='parentId']").val(treeNode.id);
        var data = getFilePath(treeNode);
        $("#wholeName").val(data);
        var nodeLength = data.split("-");
        $("#orgLevel").val(nodeLength.length + 1);//获取当前点击的节点层级

    } else if (val == 2) {   //修改弹出框
        $("#addOrgBox").css("display", "none");
        $("#updateOrgBox").css("display", "block");
        $("#updateOrgForm input[name='id']").val(treeNode.id);
        $("#updateOrgForm input[name='parentId']").val(treeNode.parentId);
        $("#updateOrgForm input[name='orgName']").val(treeNode.orgName);
        $("#updateOrgForm input[name='orgLevel']").val(treeNode.orgLevel);
        var data = treeNode.wholeName;
        var newDate = data.split("-");
        var newList = "";
        if (newDate.length > 1) {
            var list = newDate.slice(0, -1);
            for (var i = 0; i < list.length; i++) {
                newList += list[i] + "-";
            }
        } else {
            newList = newDate[0];
        }
        $("#updateOrgForm input[name='wholeName']").val(newList);
        $("#updateOrgForm input[name='remark']").val(treeNode.remark);
    } else if (val == 3) {  //3-删除操作
        DeleteOrgInfo(treeNode);
    }
}

/*树结构加载成功后默认打开顶级节点*/
var isFirst = true;

function onAsyncSuccess(event, treeId, treeNode, msg) {
    if (isFirst) {
        //获得树形图对象
        var zTree = $.fn.zTree.getZTreeObj("treeDemo");
        //获取根节点个数,getNodes获取的是根节点的集合
        var nodeList = zTree.getNodes();
        //展开第一个根节点
        zTree.expandNode(nodeList[0], true);
        //当再次点击节点时条件不符合,直接跳出方法
        isFirst = false;
    }
}

/*获取所有父节点名称*/
function getFilePath(treeObj) {
    if (treeObj == null) return "";
    var filename = treeObj.orgName;
    var pNode = treeObj.getParentNode();
    if (pNode != null) {
        filename = getFilePath(pNode) + "-" + filename;
    }
    return filename;
}


/**
 * 刷新当前节点
 */
function refreshNode() {
    /*根据 treeId 获取 zTree 对象*/
    var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
        type = "refresh",
        silent = false,
        /*获取 zTree 当前被选中的节点数据集合*/
        nodes = zTree.getSelectedNodes();
    /*强行异步加载父节点的子节点。[setting.async.enable = true 时有效]*/
    zTree.reAsyncChildNodes(nodes[0], type, silent);
}

/**
 * 刷新当前选择节点的父节点
 */
function refreshParentNode() {
    var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
        type = "refresh",
        silent = false,
        /*获取 zTree 当前被选中的节点数据集合*/
        nodes = zTree.getSelectedNodes();
    /*根据 zTree 的唯一标识 tId 快速获取节点 JSON 数据对象*/
    var parentNode = zTree.getNodeByTId(nodes[0].parentTId);
    /*选中指定节点*/
    zTree.selectNode(parentNode);
    zTree.reAsyncChildNodes(parentNode, type, silent);
}


/*新增内提交按钮点击事件*/
function submitAddOrg() {
    var $formlist = $('#addOrgForm');
    var data = $formlist.data('bootstrapValidator');
    if (data) {
        // 修复记忆的组件不验证
        data.validate();
        if (!data.isValid()) {
            return false;
        }
    }
    var formData = $("#addOrgForm").serialize();
    $.ajax({
        url: "../organ/insert",
        data: formData,
        type: "post",
        dataType: "json",
        success: function (data) {
            if (data.code == 1) {
                layer.msg(data.mess, {icon: 1});
                $("#addOrgBox").css("display", "none"); //新增方法
                $("#addOrgForm").find(":input").not(":button").val("");
                $("#chkType").val("");

                var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
                treeObj.reAsyncChildNodes(null, "refresh");
                /*refreshNode();*/ //刷新当前节点
                /*refreshParentNode();*///刷新当前节点的父节点
            } else if (data.code == 0) {
                layer.msg(data.mess, {icon: 2});
            }
        }
    })
}

/*新增按钮点击事件*/
function AddOrg() {
    var chkVal = $("#chkVal").val();
    $("#chkType").val(1);
    if (chkVal == "" || chkVal == null || chkVal == undefined) {
        layer.msg("请选择新增节点!");
    } else {
        $("#updateOrgBox").css("display", "none");
        $("#addOrgBox").css("display", "block"); //新增弹出框
        $("#addOrgForm input[name='parentId']").val(clickData.id);
        var data = getFilePath(clickData);
        $("#wholeName").val(data);
        var nodeLength = data.split("-");
        $("#orgLevel").val(nodeLength.length + 1);//获取当前点击的节点层级
    }
}


/*修改按钮点击事件*/
function UpdateOrg() {
    var chkVal = $("#chkVal").val();
    $("#chkType").val(2);
    if (chkVal == "" || chkVal == null || chkVal == undefined) {
        layer.msg("请选择修改节点!");
    } else {
        $("#addOrgBox").css("display", "none");
        $("#updateOrgBox").css("display", "block");
        $("#updateOrgForm input[name='id']").val(clickData.id);
        $("#updateOrgForm input[name='parentId']").val(clickData.parentId);
        $("#updateOrgForm input[name='orgName']").val(clickData.orgName);
        $("#updateOrgForm input[name='orgLevel']").val(clickData.orgLevel);
        var data = clickData.wholeName;
        var newDate = data.split("-");
        var newList = "";
        if (newDate.length > 1) {
            var list = newDate.slice(0, -1);
            for (var i = 0; i < list.length; i++) {
                newList += list[i] + "-";
            }
        } else {
            newList = newDate[0];
        }
        $("#updateOrgForm input[name='wholeName']").val(newList);
        $("#updateOrgForm input[name='remark']").val(clickData.remark);
    }
}

/*修改机构名称是监听机构名称输入框，取机构名以-拼接赋值给名称组合输入框的值*/
/*$('#updateorgName').bind('input propertychange', function() {
    var data = getFilePath(clickData);
    var newDate = data.split("-");
    console.log(newDate);
    var newList="";
    if(newDate.length>1){
        var list = newDate.slice(0,-1);
        for(var i=0;i<list.length;i++){
            newList += list[i]+"-"
        }
        console.log(newList);
        if(newList.length>0){
            newList = newList.substr(0, newList.length - 1);
        }
    }
    console.log(newList);
    $('#updatewholeName').val(data+"-"+$(this).val()).change();
});*/


/*修改内提交按钮点击事件*/
function submitupdateOrg() {
    var $formlist = $('#updateOrgForm');
    var data = $formlist.data('bootstrapValidator');
    if (data) {
        // 修复记忆的组件不验证
        data.validate();
        if (!data.isValid()) {
            return false;
        }
    }
    var formData = $("#updateOrgForm").serialize();
    $.ajax({
        url: "../organ/update",
        data: formData,
        type: "post",
        dataType: "json",
        success: function (data) {
            if (data.code == 1) {
                layer.msg(data.mess, {icon: 1});
                $("#updateOrgBox").css("display", "none"); //新增方法
                $("#updateOrgForm").find(":input").not(":button").val("");
                $("#chkType").val("");
                var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
                treeObj.reAsyncChildNodes(null, "refresh");
            } else if (data.code == 0) {
                layer.msg(data.mess, {icon: 2});
            }
        }
    })
}


/*删除按钮点击事件*/
function DeleteOrg() {
    $("#chkType").val(3);  //删除
    var chkVal = $("#chkVal").val();
    if (chkVal == "" || chkVal == null || chkVal == undefined) {
        layer.msg("请选择要删除的节点!");
    } else {
        DeleteOrgInfo(clickData);  //调用删除方法
    }
}

function DeleteOrgInfo(treeNode) {
    var deleteData = treeNode;
    $("#addOrgBox,#updateOrgBox").css("display", "none");
    if (deleteData.id == "") {
        layer.msg("请选择要删除的节点");
    } else {
        layer.confirm('确定要删除所选数据？', {icon: 3, title: '提示'}, function () {
            $.ajax({
                url: "../organ/delete",
                data: {"id": deleteData.id},
                type: "post",
                dataType: "json",
                success: function (data) {
                    if (data.code == 1) {
                        layer.msg(data.mess, {icon: 1});
                        $("#chkType").val("");
                        var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
                        treeObj.reAsyncChildNodes(null, "refresh");
                    } else if (data.code == 0) {
                        layer.msg(data.mess, {icon: 2});
                    }
                }
            })
        })
    }
}

/*新增弹出框内重置按钮点击事件*/
function resetAddOrg() {
    $("#addOrgForm").find(":input").not(":button,#parentId,#orgLevel,#wholeName").val("");
    $('#addOrgForm').bootstrapValidator('resetForm');//重置表单是重置表单验证
}

function resetUpdateOrg() {
    $("#updateOrgForm").find(":input").not(":button,#updateId,#updateparentId,#updatewholeName,#updateorgLevel").val("");
    $('#updateOrgForm').bootstrapValidator('resetForm');//重置表单是重置表单验证
}

/*刷新按钮点击事件*/
function refreshOrg() {
    var zTree = $.fn.zTree.getZTreeObj("treeDemo");
    zTree.reAsyncChildNodes(null, "refresh");
}


function OnRightClick(event, treeId, treeNode) {
    if (!treeNode && event.target.tagName.toLowerCase() != "button" && $(event.target).parents("a").length == 0) {
        zTree.cancelSelectedNode();
        showRMenu("root", event.clientX, event.clientY);
    } else if (treeNode && !treeNode.noR) {
        zTree.selectNode(treeNode);
        showRMenu("node", event.clientX, event.clientY);
    }
}

function showRMenu(type, x, y) {
    $("#rMenu ul").show();
    if (type == "root") {
        $("#m_del").hide();
        $("#m_check").hide();
        $("#m_unCheck").hide();
    } else {
        $("#m_del").show();
        $("#m_check").show();
        $("#m_unCheck").show();
    }

    y += document.body.scrollTop;
    x += document.body.scrollLeft;
    rMenu.css({"top": y + "px", "left": x + "px", "visibility": "visible"});

    $("body").bind("mousedown", onBodyMouseDown);
}

function hideRMenu() {
    if (rMenu) rMenu.css({"visibility": "hidden"});
    $("body").unbind("mousedown", onBodyMouseDown);
}

function onBodyMouseDown(event) {
    if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length > 0)) {
        rMenu.css({"visibility": "hidden"});
    }
}

function addTreeNode() {
    hideRMenu();
    var nodes = zTree.getSelectedNodes();
    $("#chkType").val(1);
    $("#chkVal").val(nodes[0].id);
    $("#updateOrgBox").css("display", "none");
    $("#addOrgBox").css("display", "block"); //新增弹出框
    $("#addOrgForm input[name='parentId']").val(nodes[0].id);
    var data = getFilePath(nodes[0]);
    $("#wholeName").val(data);
    var nodeLength = data.split("-");
    $("#orgLevel").val(nodeLength.length + 1);//获取当前点击的节点层级
}

function removeTreeNode() {
    hideRMenu();
    var treeNode = zTree.getSelectedNodes();
    DeleteOrgInfo(treeNode[0]);
}

function editTreeNode() {
    hideRMenu();
    var nodes = zTree.getSelectedNodes();
    var chkVal = $("#chkVal").val();
    $("#chkVal").val(nodes[0].id);
    $("#addOrgBox").css("display", "none");
    $("#updateOrgBox").css("display", "block");
    $("#updateOrgForm input[name='id']").val(nodes[0].id);
    $("#updateOrgForm input[name='parentId']").val(nodes[0].parentId);
    $("#updateOrgForm input[name='orgName']").val(nodes[0].orgName);
    $("#updateOrgForm input[name='orgLevel']").val(nodes[0].orgLevel);
    var data = nodes[0].wholeName;
    var newDate = data.split("-");
    var newList = "";
    if (newDate.length > 1) {
        var list = newDate.slice(0, -1);
        for (var i = 0; i < list.length; i++) {
            newList += list[i] + "-";
        }
    } else {
        newList = newDate[0];
    }
    $("#updateOrgForm input[name='wholeName']").val(newList);
    $("#updateOrgForm input[name='remark']").val(nodes[0].remark);
}

